export default{
	namespaced:true,
	state:{
		cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
		allChecked:false
	},
	mutations:{
		/**
		 * 改变allChecked
		 */
		changeAllChecked(state,flag){
				state.allChecked = flag
		},
		saveToStorage(state){
				//持久化存入本地
				uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		/**
		 * @param {Object} state
		 * @param {Object} cartLsit 
		 */
		updateCartLsit(state,cartLsit){
				state.cart = cartLsit
				this.commit('cart/saveToStorage')
		},
		/**
		 * 添加商品到购物车
		 * @param {Object} state
		 * @param {Object} goods 要添加的商品对象
		 */
		addToCart(state,goods){
			const finded = state.cart.find(item=>{
						return item.goods_id === goods.goods_id 
			})
			if(finded){
				finded.goods_count+=1
				finded.goods_state = goods.goods_state
			}else{
				state.cart.push(goods)
			}
			
			this.commit('cart/saveToStorage')
		}
	},
	// 模块的 getters 属性
	getters:{
		/**
		 * 购物车数量
		 * @param {Object} state
		 */
		total(state){
			let c = 0
			state.cart.forEach(item=>{
				c += item.goods_count
			})
			return c
		},
		/**
		 * 结算时选中商品数量
		 * @param {Object} state
		 */
		toPay(state){
					let m = 0
					m = state.cart.reduce((sum,item)=>{
								  if(item.goods_state === true){
											return sum + item.goods_count
									}
									return sum 
								},0)
								return m 
		/**
		 * 结算时选中商品总价格
		 * @param {Object} state
		 */
		},
		totalMoney(state){
			let m = 0
		 m = state.cart.reduce((sum,item)=>{
			  if(item.goods_state === true){
						return sum + item.goods_count*item.goods_price
				}
				return sum 
			},0)
			return m 
		}
	}
}